package com.itheima.common;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;

/**
 * @author Tang
 * @date 2023/2/21
 */
@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
    @Autowired
    private HttpSession session;

    //插入操作时，自动填充字段
    @Override
    public void insertFill(MetaObject metaObject) {
        log.info("自动填充字段【insert】");
        metaObject.setValue("createTime", LocalDateTime.now());
        metaObject.setValue("updateTime", LocalDateTime.now());
        //使用session动态获取当前登录用户id
        //Long employeeId = (Long) session.getAttribute("employeeId");

        //优化：使用ThreadLocal取值
        Long employeeId = BaseContext.getCurrentId();
        metaObject.setValue("createUser", employeeId);
        metaObject.setValue("updateUser", employeeId);
    }

    //更新操作时，自动填充字段
    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("MyMetaObjectHandler 的线程id:{}",Thread.currentThread().getId());
        log.info("自动填充字段【update】");
        metaObject.setValue("updateTime", LocalDateTime.now());

        //使用session动态获取当前登录用户id
        //Long employeeId = (Long) session.getAttribute("employeeId");

        //优化：使用ThreadLocal取值
        Long employeeId = BaseContext.getCurrentId();
        metaObject.setValue("updateUser", employeeId);
    }
}
